<template>
  <a-card class="index-change-record-card" title="林地指标变更记录">
    <template #extra>
      <a-space>
        <a-button size="small" :loading="refreshLoading" @click="refreshData">
          <template #icon>
            <icon-refresh :class="{ 'refresh-spin': refreshLoading }" />
          </template>
          刷新
        </a-button>
        <a-button size="small" type="primary" @click="showAddModal" v-perm="['lindi:indexChangeRecord:add']">
          <template #icon>
            <icon-plus />
          </template>
          新增记录
        </a-button>
      </a-space>
    </template>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data="tableData"
      :loading="props.loading"
      :pagination="pagination"
      row-key="indexChangeRecordId"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #actions="{ record }">
        <a-space>
          <a-button size="mini" type="primary" @click="editRecord(record)" v-perm="['lindi:indexChangeRecord:update']">
            <template #icon>
              <icon-edit />
            </template>
            编辑
          </a-button>
          <a-button size="mini" status="danger" @click="deleteRecord(record)" v-perm="['lindi:indexChangeRecord:delete']">
            <template #icon>
              <icon-delete />
            </template>
            删除
          </a-button>
        </a-space>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="600px"
      @ok="handleSubmit"
      @cancel="resetForm"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="townName" label="镇街名称" required>
              <a-select
                v-model="formData.townName"
                placeholder="请选择镇街名称"
                allow-search
              >
                <a-option
                  v-for="townName in townNameOptions"
                  :key="townName"
                  :value="townName"
                >
                  {{ townName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="changeQuantity" label="变更亩数" required>
              <a-input
                v-model="formData.changeQuantity"
                placeholder="请输入变更亩数"
              >
                <template #suffix>
                  <span v-if="formData.townName" style="color: #999; font-size: 12px;">
                    可调出{{ extractAvailableAcres(formData.townName) }}亩
                  </span>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import {
  IconRefresh,
  IconPlus,
  IconEdit,
  IconDelete
} from '@arco-design/web-vue/es/icon';
import {
  addIndexChangeRecordApi,
  deleteIndexChangeRecordByIndexChangeRecordIdApi,
  updateIndexChangeRecordByIndexChangeRecordIdApi,
  getPageIndexChangeRecordListApi,
  getIndexChangeRecordByIndexChangeRecordIdApi
} from '~/api/lindi/indexChangeRecord';
import { getEnableTradeTownNameListApi } from '~/api/lindi/lindiIndex';

// 定义props
const props = defineProps({
  tradeApplicationId: {
    type: String,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
});

// 响应式数据
// const loading = ref(false); // 使用父组件传递的loading状态
const refreshLoading = ref(false); // 刷新按钮的loading状态
const modalVisible = ref(false);
const modalTitle = ref('新增林地指标变更记录');
const formRef = ref(null);
const tableData = ref([]);
const editingRecord = ref(null);
const townNameOptions = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
});

// 表格列配置
const columns = [
  {
    title: '镇街名称',
    dataIndex: 'townName',
    width: 120
  },
  {
    title: '变更亩数',
    dataIndex: 'changeQuantity',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 180
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 200,
    fixed: 'right'
  }
];

// 表单数据
const formData = reactive({
  indexChangeRecordId: null,
  townName: '',
  changeQuantity: '',
  tradeApplicationId: ''
});

// 表单验证规则
const formRules = {
  townName: [
    { required: true, message: '请输入镇街名称' }
  ],
  changeQuantity: [
    { required: true, message: '请输入变更亩数' }
  ]
};

// 加载数据
const loadData = async (showLoading = false) => {
  if (showLoading) {
    refreshLoading.value = true;
  }
  
  try {
    const params = {
      current: pagination.current,
      size: pagination.pageSize,
      tradeApplicationId: props.tradeApplicationId
    };
    
    const response = await getPageIndexChangeRecordListApi(params);
    tableData.value = response.records || [];
    pagination.total = response.total || 0;
    
    if (showLoading) {
      Message.success('数据刷新成功');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    Message.error('加载数据失败：' + (error.message || error));
  } finally {
    if (showLoading) {
      refreshLoading.value = false;
    }
  }
};

// 刷新数据
const refreshData = () => {
  // 重置到第一页并刷新
  pagination.current = 1;
  loadData(true);
};

// 加载镇街名称列表
const loadTownNameOptions = async () => {
  try {
    const response = await getEnableTradeTownNameListApi();
    townNameOptions.value = response || [];
  } catch (error) {
    console.error('获取镇街名称列表失败:', error);
    Message.error('获取镇街名称列表失败：' + (error.message || error));
  }
};

// 从镇街名称中提取可调出亩数
const extractAvailableAcres = (townNameWithAcres) => {
  const match = townNameWithAcres.match(/\(可调出([\d.]+)亩\)/);
  return match ? parseFloat(match[1]) : 0;
};

// 格式化镇街名称（去掉可调出亩数部分）
const formatTownName = (townNameWithAcres) => {
  return townNameWithAcres.replace(/\(可调出[\d.]+亩\)/, '');
};

// 显示新增弹窗
const showAddModal = () => {
  modalTitle.value = '新增林地指标变更记录';
  editingRecord.value = null;
  resetForm();
  loadTownNameOptions();
  modalVisible.value = true;
};



// 编辑记录
const editRecord = (record) => {
  modalTitle.value = '编辑林地指标变更记录';
  editingRecord.value = record;
  
  // 编辑时需要找到对应的完整镇街名称（包含可调出亩数）
  loadTownNameOptions();
  
  // 延迟设置表单数据，确保镇街名称列表已加载
  setTimeout(() => {
    const fullTownName = townNameOptions.value.find(option => 
      formatTownName(option) === record.townName
    ) || record.townName;
    
    Object.assign(formData, {
      indexChangeRecordId: record.indexChangeRecordId,
      townName: fullTownName,
      changeQuantity: record.changeQuantity,
      tradeApplicationId: record.tradeApplicationId
    });
  }, 100);
  
  modalVisible.value = true;
};

// 删除记录
const deleteRecord = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条林地指标变更记录吗？',
    onOk: async () => {
      try {
        const response = await deleteIndexChangeRecordByIndexChangeRecordIdApi(record.indexChangeRecordId);
        if (response.code === 200) {
          Message.success('删除成功');
          // 如果当前页没有数据了，回到上一页
          if (tableData.value.length === 1 && pagination.current > 1) {
            pagination.current -= 1;
          }
          loadData();
        } else {
          Message.error(response.message || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        Message.error('删除失败');
      }
    }
  });
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (errors) => {
    if (errors) {
      return;
    }
    
    try {
      const selectedTownName = formData.townName;
      const submitData = {
        ...formData,
        townName: formatTownName(selectedTownName), // 格式化镇街名称
        tradeApplicationId: props.tradeApplicationId
      };
      
      let response;
      if (editingRecord.value) {
        response = await updateIndexChangeRecordByIndexChangeRecordIdApi(submitData);
      } else {
        response = await addIndexChangeRecordApi(submitData);
      }
      
      if (response.code === 200) {
        Message.success(editingRecord.value ? '更新成功' : '新增成功');
        modalVisible.value = false;
        // 保持当前页面并刷新数据
        loadData();
      } else {
        Message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      Message.error('提交失败');
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    indexChangeRecordId: null,
    townName: '',
    changeQuantity: '',
    tradeApplicationId: ''
  });
};

// 分页处理
const handlePageChange = (page) => {
  pagination.current = page;
  loadData();
};

const handlePageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  loadData();
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.index-change-record-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.refresh-spin {
  animation: refresh-rotate 1s linear infinite;
}

@keyframes refresh-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>